<template>
  <div
    class="chart-box"
    style="width: 100%; height: 100%"
    :style="{ backgroundColor: widgetOptions.setup.backgroundColor }"
  >
    <video
      v-if="!chartStatus && isPreview"
      ref="videoEl"
      style="width: 100%; height: 100%"
      :autoplay="true"
      controls
    ></video>
    <img v-else style="width: 100%; height: 100%" :src="videoImg" />
    <ChartEmpty v-if="chartStatus" :chartStatus="chartStatus" />
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'
// import videoMovie from '@/assets/video/movie.mp4'
import { AlgengineApi } from '@/api/vmiot/algengine'
import ChartEmpty from '../../components/chartEmpty.vue'
import Hls from 'hls.js'
import videoImg from '@/assets/video-cover.jpg'

// 接收父组件传入的值
const props = defineProps({
  widgetOptions: {
    type: Object as PropType<Record<string, any>>, // 或更具体的类型
    required: true
  },
  isPreview: {
    type: Boolean,
    default: false
  }
})

const videoEl = ref<HTMLVideoElement | null>(null)
const videoUrl = ref()
const chartStatus = ref<string>(
  props.isPreview && !props.widgetOptions.data.signal ? 'taskError' : ''
)

const signal = computed(() => props.widgetOptions.data.signal)

const getData = async () => {
  if (signal.value.signalAccessType.includes('HTTP')) {
    try {
      const res = await AlgengineApi.getSignalRealtime({
        signalAccessParams: signal.value.signalAccessParams
      })

      videoUrl.value = res.msgPack.value.hls
      playVideo()
    } catch (error) {
      chartStatus.value = 'error'
    }
  }
}

let hls
const playVideo = () => {
  if (Hls.isSupported() && videoEl.value) {
    hls = new Hls()
    hls.loadSource(videoUrl.value)
    hls.attachMedia(videoEl.value)
    hls.on(Hls.Events.MANIFEST_PARSED, () => {
      videoEl.value?.play()
    })
  } else if (videoEl.value?.canPlayType('application/vnd.apple.mpegurl')) {
    videoEl.value.src = videoUrl.value
    videoEl.value.play()
  }
}

onMounted(() => {
  if (props.isPreview) {
    getData()
  }
})

onBeforeUnmount(() => {
  if (hls) {
    hls.destroy()
    hls = null
  }
})
</script>

<style scoped></style>
